package com.hmjk.health.background.data;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.format.Time;
import android.util.Log;

import com.hmjk.health.HealthApp;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.NetService;
import com.hmjk.health.util.MEM_FACE;

public class MemberFaceUpdated extends DataUpdated{
	private static String TAG = MemberFaceUpdated.class.getSimpleName();
	
	private ArrayList<String> mUIDArray = new ArrayList<String>();
	private int index = 0;
	private HashMap<String, MEM_FACE> mFaceMap = new HashMap<String, MEM_FACE>();
	private boolean working = false;
	
	private void logd(String info){
		Log.d(TAG, info);
	}
	
	public MemberFaceUpdated(HealthApp app, DataManager dm) {
		super(app, dm);
		UPDATE_TIME = 2 * 60 * 60 * 1000;
	}

	@Override
	public void setUserData(Object data) {
		logd("setUserData");
		String[] in = (String[]) data;
		int oldsize = mUIDArray.size();
		
		mUIDArray.clear();
		index = 0;
		reqTime = 0;
		if((in == null) || (in.length == 0))
			return;
		
		for(String uid:in){
			mUIDArray.add(uid);
			MEM_FACE d = mFaceMap.get(uid);
			logd("setUserData get uid="+uid+ " MEM_FACE = "+d);
			if(d == null){
				d = new MEM_FACE();
				d.uid = uid;
				mFaceMap.put(uid, d);
				logd("setUserData get uid="+uid+ " new MEM_FACE" );
			}
			if(d.path == null){
				d.path = mApp.getDevFaceFileName(d.uid);
			}
			//logd("setUserData get uid="+uid+ " path="+d.path );
		}
		
		if(oldsize == 0){
			grab();
		}
	}
	
	private void loadBitmap(MEM_FACE d){
		InputStream bmpIs = null;
		try{
			Uri imageUri = Uri.parse("file://" + d.path);
			d.recycle();
			logd("MEM_FACE loadBitmap "+d.uid);
			bmpIs = mApp.getContentResolver().openInputStream(imageUri);
			
			d.bitmap = BitmapFactory.decodeStream(bmpIs);
			bmpIs.close();
		}catch(FileNotFoundException e){
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public long delay() {
		long curMs = System.currentTimeMillis();
		long del = curMs - upTime;
		logd("delay curMs="+curMs+" upTime="+upTime+" del="+del);
		if(del >= UPDATE_TIME){
			logd("delay 0");
			return 0;
		}else{
			logd("delay (UPDATE_TIME - del) = "+(UPDATE_TIME - del));
			return (UPDATE_TIME - del);
		}
	}
	
	private void checkFace(String uid, String check_uid){
		MEM_FACE d = mFaceMap.get(check_uid);
		if(d == null){
			d = new MEM_FACE();
			d.uid = check_uid;
			mFaceMap.put(check_uid, d);
		}
		
		if(d.path == null){
			d.path = mApp.getFaceFileName(d.uid);
		}
		
		long lstamp = 0;
		if(d.path != null){
			int pos = d.path.lastIndexOf(File.separator);
			String name = d.path.substring(pos+1);
			int len = d.uid.length();
			String sstamp = name.substring(len);
			pos = sstamp.lastIndexOf(".");
			if(pos > 0){
				sstamp = sstamp.substring(0, pos);
			}
			lstamp = Long.parseLong(sstamp);
		}
		Intent si = new Intent(NetService.GET_DATA_ACTION);
		si.putExtra("sub_act", NetService.CHECK_USER_FACE);
		si.putExtra("uid", uid);
		si.putExtra("vuid", d.uid);
		si.putExtra("vstamp", lstamp);
			
		Time t = new Time();
		t.setToNow();
		String stamp = "CHECK_USER_FACE_MEM" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
		mApp.startService(si);
	}

	private void download(String uid){
		Log.d("NET_DEBUG","download uid = " + uid);
		String downfilePath = mApp.getDownloadFaceFolder();
		downfilePath += "/" + uid + ".jpg";
		Intent si = new Intent(NetService.DOWNLOAD_ACTION);
		si.putExtra("sub_act", NetService.DOWNLOAD_USER_FACE);
		si.putExtra("uid", uid);
		si.putExtra("type", "m");
		si.putExtra("path", downfilePath);
		
		Time t = new Time();
		t.setToNow();
		String stamp = "DOWNLOAD_USER_FACE_MEM" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
		mApp.startService(si);
	}
	
	private void doNextRequest(){
		String uid = mApp.getUID();
		if(uid == null){
			Log.e(TAG, "doNextRequest uid == null stoped!");
			working = false;
		}
		int size = mUIDArray.size();
		if(index < size){
			String check_uid = mUIDArray.get(index);
			checkFace(uid,check_uid);
			index ++;
		}else{
			working = false;
		}
	}
	
	private void doRequest(String uid){
		int size = mUIDArray.size();
		if(size > 0){
			index = 0;
			String check_uid = mUIDArray.get(index);
			working = true;
			checkFace(uid,check_uid);
			index ++;
		}else{
			Intent i = new Intent(DataManager.DATA_UPDATE_ACTION);
			i.putExtra("type",DataManager.F_MEMBERFACE);
			i.putExtra("state", false);
			i.putExtra("uid", "");
			mApp.sendBroadcast(i);
		}
	}

	@Override
	public boolean grab() {
		String uid = mApp.getUID();
		logd("grab uid="+uid);
		if(uid == null)
			return false;
		
		if(working){
			logd("grab working now");
			return false;
		}
		
		if(mUIDArray.size() == 0){
			logd("grab not tid specified to be check");
			return false;
		}
		
		long curMs = System.currentTimeMillis();
		logd("grab curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > UPDATE_TIME){
			doRequest(uid);
			reqTime = curMs;
			logd("grab req sent!");
			return true;
		}
		return false;
	}

	@Override
	public boolean grabByUser() {
		String uid = mApp.getUID();
		logd("grabByUser uid="+uid);
		if(uid == null)
			return false;
		
		if(working){
			logd("grabByUser downloading");
			return false;
		}
		if(mUIDArray.size() == 0){
			logd("grabByUser not tid specified to be check");
			return false;
		}
		
		long curMs = System.currentTimeMillis();
		logd("grabByUser curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > 30 * 1000){
			doRequest(uid);
			reqTime = curMs;
			logd("grabByUser req sent!");
			return true;
		}
		return false;
	}

	@Override
	public void receive(String stamp, String sjson) {
		if(stamp.startsWith("CHECK_USER_FACE_MEM")){
			if(sjson != null){
				boolean update = false;
				String validuid = "";
				try {
					JSONObject json = new JSONObject(sjson);
					int code = json.getInt("code");
					if(code == 200){
						String state = json.getString("state");
						JSONObject sd = json.getJSONObject("senddata");
						validuid = sd.getString("validuid");
						if(state.equalsIgnoreCase("00")){
							update = false;
							upTime = System.currentTimeMillis();
						}else if(state.equalsIgnoreCase("22")){
							update = true;
						}else{
							Log.e(TAG, "receive error state:"+state+" from network");
						}
					}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				
				if(update == false){
					doNextRequest();
					Intent i = new Intent(DataManager.DATA_UPDATE_ACTION);
					i.putExtra("type",DataManager.F_MEMBERFACE);
					i.putExtra("state", update);
					i.putExtra("uid", validuid);
					mApp.sendBroadcast(i);
				}else{
					download(validuid);
				}	
			}
		}else if(stamp.startsWith("DOWNLOAD_USER_FACE_MEM")){
			if(sjson != null){
				boolean update = false;
				String uid="";
				try {
					JSONObject json = new JSONObject(sjson);
					int code = json.getInt("code");
					
					if(code == 200){
						String state = json.getString("state");
						if(state.equalsIgnoreCase("00")){
							JSONObject sd = json.getJSONObject("senddata");
							JSONObject recdata = json.getJSONObject("recdata");
							if(sd != null){
								uid = sd.getString("uid");
								clearCurrent(uid);
								if(recdata != null){
									long time = recdata.getLong("timestamp");
									String filepath = json.getString("downloadfile");
									File f = new File(filepath);
									String facePath = mApp.getFaceFolder() + "/" + uid + time + ".jpg";
									File faceFile = new File(facePath);
									f.renameTo(faceFile);
								}
								
							}
							update = true;
							//upTime = System.currentTimeMillis();
							
						}
						//TODO: update the image of tid
					}else{
						//upTime = System.currentTimeMillis();
						update = false;
					}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
				
				doNextRequest();
				Intent i = new Intent(DataManager.DATA_UPDATE_ACTION);
				i.putExtra("type",DataManager.F_MEMBERFACE);
				i.putExtra("state", update);
				i.putExtra("uid", uid);
				mApp.sendBroadcast(i);
			}
		}
	}
	
	public void clearCurrent(String uid){
		MEM_FACE d = mFaceMap.get(uid);
		d.recycle();
		if(d.path == null){
			d.path = mApp.getFaceFileName(d.uid);
		}
		if(d.path != null){
			File f = new File(d.path);
			if(f.exists())
				f.delete();
		}
		
		d.path = null;
	}

	@Override
	public Object check(String[] arg) {
		logd("MEM_FACE check");
		if(mUIDArray.size() > 0){
			if(arg == null){
				Set<String> keys = mFaceMap.keySet();
				for(String k:keys){
					MEM_FACE d = mFaceMap.get(k);
					logd("MEM_FACE check "+d.uid);
					
					if(d.path == null){
						d.path = mApp.getFaceFileName(d.uid);
					}
					logd("MEM_FACE check "+d.uid + " path="+d.path);
					
					if(d.path == null){
						d.recycle();
					}else{
						if(d.bitmap == null){
							loadBitmap(d);
						}
					}
				}
			
				return mFaceMap;
			}else if((arg.length == 1) && (arg[0] != null) && (arg[0].trim().length() > 0)){
				String uid = arg[0];
				MEM_FACE f = mFaceMap.get(uid);
				if(f != null){
					logd("MEM_FACE check "+uid);
					if(f.path == null){
						f.path = mApp.getFaceFileName(f.uid);
					}
					if(f.path == null){
						f.recycle();
					}else{
						if(f.bitmap == null){
							loadBitmap(f);
						}
					}
				}
				return f;
			}
		}
		return null;
	}
	
	@Override
	public boolean commit(Object data) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void release() {
		if(mFaceMap.isEmpty())
			return;
		
		Set<String> keys = mFaceMap.keySet();
		for(String k:keys){
			MEM_FACE f = mFaceMap.get(k);
			if(f != null)
				f.clear();
		}
		mFaceMap.clear();
	}

}
